﻿using System;
using System.Data;
using Infragistics.Win;
using System.ServiceModel;
using System.Windows.Forms;
using System.Collections.Generic;
using Infragistics.Win.UltraWinToolbars;

namespace DMSClient
{
    public partial class MainMenu : Form
    {
        private WSHttpBinding httpBinding;
        private EndpointAddress address;
        private TextBox tbRol = new TextBox();
        private TextBox tbUser = new TextBox();

        public MainMenu()
        {
            InitializeComponent();
            this.MainToolbar.Ribbon.ApplicationMenu.ToolAreaRight.Tools["ButtonTool1"].SharedProps.Enabled = false;
            this.MainToolbar.Ribbon.ApplicationMenu.ToolAreaRight.Tools["ButtonTool1"].SharedProps.AppearancesSmall.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
            this.MainToolbar.Ribbon.ApplicationMenu.ToolAreaRight.Tools["ButtonTool1"].SharedProps.AppearancesSmall.Appearance.FontData.SizeInPoints = 16;

            httpBinding = new WSHttpBinding();
            httpBinding.MaxReceivedMessageSize = Int32.MaxValue;
            httpBinding.MaxBufferPoolSize = Int32.MaxValue;
            httpBinding.Security.Mode = SecurityMode.None;
            httpBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
        }

        private void MainToolbar_ToolClick(object sender, ToolClickEventArgs e)
        {
            ComboBoxTool cb = MainToolbar.Tools["Environment"] as ComboBoxTool;
            Properties.Settings.Default.CurrentEnv = cb.ValueList.ValueListItems[cb.SelectedIndex].DisplayText;
            Properties.Settings.Default.CurrentEnvDes = Properties.Settings.Default.CurrentEnv;
            Properties.Settings.Default.Save();
            switch (e.Tool.Key)
            {
                case "CCFOT":
                    try
                    {
                        CCFOT ccfot = new CCFOT();
                        ccfot.MdiParent = this;
                        ccfot.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Stock":
                    try
                    {
                        frmImportStock importStock = new frmImportStock();
                        importStock.MdiParent = this;
                        importStock.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Quota":
                    try
                    {
                        Distributors.Quota qt = new Distributors.Quota();
                        qt.MdiParent = this;
                        qt.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Store":
                    try
                    {
                        Distributors.Store st = new Distributors.Store();
                        st.MdiParent = this;
                        st.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "QuotaU":
                    try
                    {
                        Unilever.QuotaU qut = new DMSClient.Unilever.QuotaU();
                        qut.MdiParent = this;
                        qut.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Visit":
                    try
                    {
                        Visit v = new Visit();
                        v.MdiParent = this;
                        v.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Cabinet":
                    try
                    {
                        Distributors.Cabinet cab = new Distributors.Cabinet();
                        cab.MdiParent = this;
                        cab.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "RegionUser":
                    try
                    {
                        RegionUser ru = new RegionUser();
                        ru.MdiParent = this;
                        ru.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "City":
                    try
                    {
                        City city = new City();
                        city.MdiParent = this;
                        city.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Product":
                    try
                    {
                        Product product = new Product();
                        product.MdiParent = this;
                        product.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "ImportClass":
                    try
                    {
                        frmImportClassification importClass = new frmImportClassification();
                        importClass.MdiParent = this;
                        importClass.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Currency":
                    try
                    {
                        Currency cur = new Currency();
                        cur.MdiParent = this;
                        cur.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Route":
                    try
                    {
                        Route route = new Route();
                        route.MdiParent = this;
                        route.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Conversion":
                    try
                    {
                        ComboBoxTool combo = MainToolbar.Tools["Environment"] as ComboBoxTool;
                        if (combo.Value.ToString().Equals("PILOT"))
                        {
                            MessageBox.Show(this, "This option is not allowed for Pilot enviroment!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            return;
                        }
                        Conversion con = new Conversion();
                        con.MdiParent = this;
                        con.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "FTPReport":
                    try
                    {
                        FTP ftp = new FTP();
                        ftp.MdiParent = this;
                        ftp.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "ConversionTable":
                    try
                    {
                        ConversionList conList = new ConversionList();
                        conList.MdiParent = this;
                        conList.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "AdmUnit":
                    try
                    {
                        Unit uni = new Unit();
                        uni.MdiParent = this;
                        uni.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                /*Falta definir con leo cómo es la cuestion para cada formulario*/
                case "Order":
                    try
                    {
                        Distributors.Orders frmOrders = new Distributors.Orders();
                        frmOrders.MdiParent = this;
                        frmOrders.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Invoice":
                    try
                    {
                        Distributors.Invoices frmInvoices = new Distributors.Invoices();
                        frmInvoices.MdiParent = this;
                        frmInvoices.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Assortment":
                    try
                    {
                        Unilever.Surtidos frmSurtidos = new Unilever.Surtidos();
                        frmSurtidos.MdiParent = this;
                        frmSurtidos.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "User":
                    try
                    {
                        General.User frmUser = new General.User();
                        frmUser.MdiParent = this;
                        frmUser.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "productGold":
                    try
                    {
                        ComboBoxTool comboX = MainToolbar.Tools["Environment"] as ComboBoxTool;
                        if (!comboX.ValueList.ValueListItems[comboX.SelectedIndex].Tag.Equals("USA"))
                        {
                            MessageBox.Show(this, "USA's environments Only", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            return;
                        }
                        Unilever.productGold pro = new Unilever.productGold();
                        pro.MdiParent = this;
                        pro.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "Close":
                    this.Close();
                    break;
                case "LogOut":
                    foreach (Form f in this.MdiChildren)
                    {
                        f.Close();
                    }
                    cleanKeys();
                    MainMenu_Load(sender, new EventArgs());
                    break;
                case "Validate":
                    ValidateProductMaster vpm = new ValidateProductMaster();
                    vpm.MdiParent = this;
                    vpm.Show();
                    break;
                case "mngError":
                    bool esta = false;
                    int activo = -1;
                    foreach (System.Windows.Forms.Form hijo in this.MdiChildren) {
                        activo++;
                        if (hijo.Name.Equals("ErrorManager")) {
                            esta = true;
                            break;
                        } 
                    }
                    if (esta)
                    {
                        MessageBox.Show(this, "An instance of this option is running", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.ActivateMdiChild(this.MdiChildren[activo]);
                        this.MdiChildren[activo].BringToFront();
                        
                    }
                    else {
                        General.ErrorManager em = new General.ErrorManager();
                        em.MdiParent = this;
                        em.Show();
                    }
                    break;
                case "RoleGrant":
                    General.AccessGrant ag = new General.AccessGrant();
                    ag.MdiParent = this;
                    ag.Show();
                    break;
                case "EmailList":
                    try
                    {
                        General.EmailList emailList = new DMSClient.General.EmailList();
                        emailList.MdiParent = this;
                        emailList.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "EmailGroup":
                    try
                    {
                        General.EmailGroup emailGroup = new DMSClient.General.EmailGroup();
                        emailGroup.MdiParent = this;
                        emailGroup.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "scheduler":
                    try
                    {
                        General.Scheduler scheduler = new DMSClient.General.Scheduler();
                        scheduler.MdiParent = this;
                        scheduler.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                case "ChangePassword":
                    try
                    {
                        General.ChangePass changePass = new DMSClient.General.ChangePass(tbUser.Text);
                        changePass.MdiParent = this;
                        changePass.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;
                default:
                    changeStyle(e.Tool.Key);
                    break;
            }
        }

        public void changeStyle(string style)
        {
            System.IO.MemoryStream ms = null;
            try
            {
                switch (style)
                {
                    case "OfficeBlue":
                        ms = new System.IO.MemoryStream(Properties.Resources.Office2007Blue);
                        break;
                    case "OfficeBlack":
                        ms = new System.IO.MemoryStream(Properties.Resources.Office2007Black);
                        break;
                    case "OfficeSilver":
                        ms = new System.IO.MemoryStream(Properties.Resources.Office2007Silver);
                        break;
                    case "Trendy":
                        ms = new System.IO.MemoryStream(Properties.Resources.Trendy);
                        break;
                    case "Pear":
                        ms = new System.IO.MemoryStream(Properties.Resources.Pear);
                        break;
                    case "Windows7":
                        ms = new System.IO.MemoryStream(Properties.Resources.Windows7);
                        break;
                    case "VS2010":
                        ms = new System.IO.MemoryStream(Properties.Resources.VS2010);
                        break;
                    case "VS2008":
                        ms = new System.IO.MemoryStream(Properties.Resources.VS2008);
                        break;
                    default:
                        ms = new System.IO.MemoryStream(Properties.Resources.Office2007Blue);
                        style = "OfficeBlue";
                        break;
                }
                Infragistics.Win.AppStyling.StyleManager.Load(ms, true);
                ms.Close();
                this.Invalidate();
                this.Update();
                Properties.Settings.Default.Skin = style;
                Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {

            }
        }

        private void MainMenu_Load(object sender, EventArgs e)
        {
            Login logIn = new Login(ref tbRol, ref tbUser);
            if (logIn.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                logIn.Close();
                address = new EndpointAddress(Properties.Settings.Default.Server);
                DMSServices.DMSServicesClient ObjSrv = new DMSServices.DMSServicesClient(httpBinding, address);
                DataTable dt = null;
                try
                {
                    ObjSrv.Open();
                    dt = ObjSrv.getEnvironments();
                    ObjSrv.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this,
                        "Error trying to load available environments, check your network connection and if server is running", 
                        this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    MainMenu_Load(sender, e);
                    return;
                }
                if (dt.Rows.Count < 1)
                {
                    MessageBox.Show(this,
                        "No environments availables",
                        this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    MainMenu_Load(sender, e);
                    return;
                }
                ComboBoxTool cb = new ComboBoxTool("Environment");
                this.MainToolbar.Tools.Add(cb);

                ValueList environmentsList = new ValueList();
                ValueListItem item = null;
                int index = 0;
                foreach (DataRow env in dt.Rows)
                {
                    if (!env["name"].ToString().Equals("DMSTools"))
                    {
                        item = new ValueListItem(env["type"], env["name"].ToString());
                        item.Tag = env["project"].ToString();
                        environmentsList.ValueListItems.Add(item);
                        if (item.DisplayText.Equals(Properties.Settings.Default.CurrentEnv))
                        {
                            index = environmentsList.ValueListItems.Count - 1;
                        }
                    }
                }
                cb.ValueList = environmentsList;
                cb.SelectedIndex = index;
                this.MainToolbar.Ribbon.QuickAccessToolbar.Tools.AddTool("Environment");
                if (!LoadToolbar())
                {
                    cleanKeys();
                    MainMenu_Load(sender, e);
                    return;
                }
            }
            else
            {
                Close();
            }
        }

        private void cleanKeys()
        {
            foreach (RibbonTab rt in this.MainToolbar.Ribbon.Tabs)
            {
                foreach (RibbonGroup rg in rt.Groups)
                {
                    foreach (ToolBase tb in rg.Tools)
                    {
                        this.MainToolbar.Tools.Remove(tb);
                    }
                    rg.Tools.Clear();
                }
                rt.Groups.Clear();
            }
            this.MainToolbar.Tools.Remove(this.MainToolbar.Tools["Environment"]);
            this.MainToolbar.Ribbon.Tabs.Clear();
            this.MainToolbar.Ribbon.QuickAccessToolbar.Tools.Clear();
        }

        private DataTable filtroTabla(DataTable tab, string filtro)
        {
            try
            {
                DataRow[] rows;
                DataTable dtNew = tab.Clone();

                rows = tab.Select(filtro);

                foreach (DataRow row in rows)
                {
                    dtNew.ImportRow(row);
                }
                return dtNew;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return null;
            }
        }

        private bool LoadToolbar()
        {
            string errorMSG = "Error trying to load application functions, check your network connection and if server is running";
            string errorMSGRes = "Error trying to load application functions, server side error";

            DMSServices.DMSServicesClient ObjSrv = new DMSServices.DMSServicesClient(httpBinding, address);
            DataTable dt = null;
            DataSet ds = new DataSet("dsMenu");
            DataTable dtMenu = new DataTable();
            try
            {
                ObjSrv.Open();
                dtMenu = ObjSrv.getMenu(tbRol.Text);
                dt = filtroTabla(dtMenu, "ObjetoTipo = 'TAB'");
                ObjSrv.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, errorMSG, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            if (dt == null)
            {
                MessageBox.Show(this, errorMSGRes, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            for (int i = 0; i < dt.Rows.Count; i++) {
                this.MainToolbar.Ribbon.Tabs.Add(new RibbonTab(dt.Rows[i]["ObjetoKey"].ToString(), dt.Rows[i]["ObjetoDescripcion"].ToString()));
                DataTable dtGruops = new DataTable();
                dtGruops = filtroTabla(dtMenu, "contenedor='" + dt.Rows[i]["ObjetoKey"].ToString() + "' and ObjetoTipo='GROUP'");
                for (int j = 0; j < dtGruops.Rows.Count; j++) {
                    this.MainToolbar.Ribbon.Tabs[dtGruops.Rows[j]["contenedor"].ToString()].Groups.Add(new RibbonGroup(dtGruops.Rows[j]["ObjetoKey"].ToString(), dtGruops.Rows[j]["ObjetoDescripcion"].ToString()));
                    DataTable dtTools = new DataTable();
                    dtTools = filtroTabla(dtMenu, "contenedor='" + dtGruops.Rows[j]["ObjetoKey"].ToString() + "' and ObjetoTipo='TOOL'");
                    foreach (DataRow tool in dtTools.Rows)
                    {
                        string key = tool["Objetokey"].ToString();
                        ButtonTool tl = new ButtonTool(key);
                        if (tool["Objetoimagen"] != System.DBNull.Value)
                        {
                            tl.SharedProps.AppearancesLarge.Appearance.Image = Bytes2Image((byte[])tool["Objetoimagen"]);
                        }
                        tl.SharedProps.Caption = tool["ObjetoDescripcion"].ToString();
                        try
                        {
                            this.MainToolbar.Tools.Add(tl);
                        }
                        catch (Exception ex)
                        {

                        }
                        this.MainToolbar.Ribbon.Tabs[dt.Rows[i]["ObjetoKey"].ToString()].Groups[tool["contenedor"].ToString()].Tools.AddTool(key).InstanceProps.PreferredSizeOnRibbon = RibbonToolSize.Large;
                    }
                }
            }
            return true;
        }

        private System.Drawing.Image Bytes2Image(byte[] bytes)
        {
            if (bytes == null) return null;
            System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
            System.Drawing.Bitmap bm = null;
            try
            {
                bm = new System.Drawing.Bitmap(ms);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return bm;
        }
    }
}